package net.xinqushi.design.strategy;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 *   分账策略
 */
@Service
public class DivisionStrategy implements ApplicationContextAware {

    private Map<Assets, IDivision> divisionMap = new HashMap<>();
    public IDivision getDivision(Assets assets){return divisionMap.get(assets);}

    /**
     *   使用Spring特性  好于  每次new一个对象
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext){
        //根据接口类型返回相应的所有bean
        Map<String, IDivision> beanMap = applicationContext.getBeansOfType(IDivision.class);
        beanMap.forEach( (beanName , bean) ->{
            divisionMap.put(bean.getType() , bean);
        });
    }

    public static void main(String[] args) {
        // 将所有分账  放入一个List  ，循环执行相应的策略
        // 调用JMX 分账
        DivisionStrategy divisionStrategy = new DivisionStrategy();// GetBySpring
        IDivision division = divisionStrategy.getDivision(Assets.JMX);
        division.division();
    }

    /**
     * 根据事件类型调用不同的实现类处理
     */
    public void division(String eventType) {
        IDivision division = divisionMap.get(eventType);
        if (division == null){
            throw new RuntimeException("未找到事件处理实现类，division：" + division);
        }
        division.division();
    }
}

interface IDivision{
    /**
     *   处理分账
     */
    void division();

    Assets getType();

}
@Service
class ClxDivision implements IDivision{

    @Override
    public void division() {
        //磁力线逻辑

    }

    @Override
    public Assets getType() {
        return Assets.CLX;
    }
}
@Service
class JmxDivision implements IDivision{

    @Override
    public void division() {
        //金美信

    }

    @Override
    public Assets getType() {
        return Assets.JMX;
    }
}
enum Assets{
    JMX,CLX,CAI360,NY,BYXF,
}
